import Vue from 'vue'
import VueRouter from 'vue-router'
import store from "@/store";
import {userMenu} from "@/api/user";
import {listToTree} from "@/utils/treeUtil";

Vue.use(VueRouter)

const routes = [
    {
        path: '/',
        redirect: '/login'
    },
    {
        path: '/login',
        name: 'login',
        // which is lazy-loaded when the route is visited     懒加载模式 组件被访问时 在加载
        component: () => import('@/views/login/LoginView.vue')
    },
    {
        path: '/index',
        name: 'index',
        redirect: '/home',
        component: () => import('@/views/layout/IndexView.vue'),
        children: []
    }
]

const router = new VueRouter({
    routes
})


// 路由守卫     动态菜单数据的获取   非法请求的拦截    to: 目标路由    from : 原始路由     next 放行路由
router.beforeEach(async (to, from, next) => {
    let path = to.path;
    let token = sessionStorage.getItem("token");

    if (!token && to.path != "/login") {
        next("/login")
    }

    if (token && to.path == "/login") {
        next("/home")
    }

    if (token) {
        if (store.state.menuList.length == 0) {
            // 发送请求获取用户的菜单
            let {data} = await userMenu()
            let dbMenu = listToTree(data.menu)  // [{},{}]
            let menu = [
                {
                    title: '首页',
                    icon: 'el-icon-s-home',
                    path: '/home'
                },
                ...dbMenu
            ]
            store.commit("initMenu", menu)
            // TODO  动态路由  过滤用户权限  isMenu=1
            let menuRouter = data.menu.filter(permission => permission.isMenu == 1)
                .map(permission => {
                    return {
                        path: permission.path,
                        component: () => import('@/views/' + permission.model + '/' + permission.component)
                    }
                })  // [{},{}]

            let lastRouter = [
                {
                    path: '/home',
                    name: 'home',
                    component: () => import('@/views/home/HomeView.vue')
                },
                ...menuRouter,
                {
                    path: '/**',
                    name: 'page404',
                    component: () => import('@/views/page404/Page404View.vue')
                }

            ]
            // 遍历路由列表  添加动态路由到 index
            lastRouter.forEach(rt => {
                router.addRoute("index", rt)
            })

            //重定向路由
            next(to.path)
        }

    }
    next();
})


export default router
